document.addEventListener('DOMContentLoaded', () => {
    const loginForm = document.getElementById('loginForm');
    const userInfo = document.getElementById('userInfo');
    const loginBtn = document.getElementById('loginBtn');
    const logoutBtn = document.getElementById('logoutBtn');
    const phone = document.getElementById('phone');
    const password = document.getElementById('password');
    const phoneError = document.getElementById('phoneError');
    const passwordError = document.getElementById('passwordError');
    const status = document.getElementById('status');

    // 检查登录状态
    try {
        chrome.storage.local.get(['isLoggedIn'], (result) => {
            if (result.isLoggedIn) {
                loginForm.style.display = 'none';
                userInfo.style.display = 'block';
            }
        });
    } catch (error) {
        console.error('存储API访问失败:', error);
    }

    // 登录按钮点击事件
    loginBtn.addEventListener('click', () => {
        // 重置错误提示
        phoneError.style.display = 'none';
        passwordError.style.display = 'none';
        status.textContent = '';

        // 验证手机号
        if (!/^1[3-9]\d{9}$/.test(phone.value)) {
            phoneError.style.display = 'block';
            return;
        }

        // 验证密码
        if (!password.value) {
            passwordError.style.display = 'block';
            return;
        }

        // 登录验证
        validateLogin(phone.value, password.value).then((result) => {
            if (result) {
                try {
                    chrome.storage.local.set({ isLoggedIn: true }, () => {
                        loginForm.style.display = 'none';
                        userInfo.style.display = 'block';
                        status.textContent = '登录成功！';
                        
                        // 通知content script登录状态改变
                        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                            if (tabs[0] && tabs[0].id) {
                                chrome.tabs.sendMessage(tabs[0].id, {
                                    action: 'loginStatusChanged',
                                    isLoggedIn: true
                                });
                            }
                        });
                    });
                    getLocal()
                } catch (error) {
                    console.error('存储API访问失败:', error);
                    status.textContent = '登录失败，请稍后重试！';
                }
            } else {
                status.textContent = '手机号或密码错误！';
            }
        });
    });

    // 退出登录按钮点击事件
    logoutBtn.addEventListener('click', async () => {
        try {
            // 获取存储的token
            const { accessToken, xAccessToken } = await new Promise((resolve) => {
                chrome.storage.local.get(['accessToken', 'xAccessToken'], resolve);
            });

            // 清除本地存储的信息
            chrome.storage.local.remove(['accessToken', 'xAccessToken', 'userInfo'], () => {
                chrome.storage.local.set({ isLoggedIn: false }, () => {
                    loginForm.style.display = 'block';
                    userInfo.style.display = 'none';
                    phone.value = '';
                    password.value = '';
                    status.textContent = '已退出登录';

                    // 通知content script登录状态改变
                    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                        if (tabs[0] && tabs[0].id) {
                            chrome.tabs.sendMessage(tabs[0].id, {
                                action: 'loginStatusChanged',
                                isLoggedIn: false
                            });
                        }
                    });
                });
            });
            getLocal()
        } catch (error) {
            console.error('退出登录失败:', error);
            status.textContent = '退出登录失败，请稍后重试！';
        }
    });
});

// 模拟登录验证函数
async function validateLogin(phone, password) {
    try {
        const response = await fetch('https://guang.wx.meikeai.net/api/auth/admin', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userName: phone,
                password: password
            })
        });

        // 从响应头中获取token
        const accessToken = response.headers.get('access-token');
        const xAccessToken = response.headers.get('x-access-token');
        console.log('响应头中的token:', { accessToken, xAccessToken });

        const data = await response.json();
        console.log('登录响应:', data);

        if (data.statusCode == 200 && data.succeeded) {
            // 检查是否至少有一个token存在且非空
            if ((accessToken && accessToken.trim() !== '') || (xAccessToken && xAccessToken.trim() !== '')) {
                try {
                    chrome.storage.local.set({
                        accessToken: accessToken || '', // 保存access-token，如果不存在则保存空字符串
                        xAccessToken: xAccessToken || '', // 保存x-access-token，如果不存在则保存空字符串
                        userInfo: data.data
                    });
                    getLocal(); // 查看存储内容
                } catch (error) {
                    console.error('保存用户信息失败:', error);
                }
            } else {
                console.warn('未找到有效的token在响应头中');
            }
            return true;
        }
        return false;
    } catch (error) {
        console.error('登录请求失败:', error);
        return false;
    }
}
// 查看本地缓存内容

function getLocal(){
    chrome.storage.local.get(null, (items) => {
        console.log('当前存储的所有内容:', items);
    });
}